<?php

namespace App\Admin\Controllers;

use App\Models\AdminUser;
use App\Models\AfterSales;
use App\Models\Area;
use App\User;
use App\Util\Tool;
use App\Util\Url;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;

/**
 * 此项目由百凯伦公司研发，后面省略一万字
 */
class ReimburseController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '售后列表';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new AfterSales());
        $userid = auth()->user()->id ?? 0;
        $is_work = auth()->user()->is_work;
        $where = [];
        if($is_work >0){
            $where [] = ['work_id', '=', $is_work];//工作室
            $where [] = ['order_source', '=', 1];//商品类型
        }else{
            $where [] = ['suppliers_id', '=', $userid];//供应商//读取当前登录供应商的产品
            $where [] = ['order_source', '=', 2];//商品类型
        }
        $grid->model()->where($where)->orderByDesc('id');
        $grid->disableExport();//禁止导出
        $grid->disableCreateButton();//禁用创建按钮
        $grid->actions(function (Grid\Displayers\Actions $actions) {

            $actions->disableDelete(); //禁止行级删除路由
            $actions->disableEdit();//禁止行级编辑路由
            //仅退款、
            //status审核状态 0未审核 after_type 1仅退款 after_status处理状态0未完成
            if ($actions->row->after_type == 1 && $actions->row->after_status == 0 && $actions->row->status == 0) {
                $actions->append("<a class='btn btn-xs action-btn btn-success grid-row-pass' data-id='{$actions->getKey()}'><i class='fa fa-check' title='同意退款'>同意退款</i></a>");
            }
            //退货退款、显示审核按钮
            //after_type 2退货退款 after_status 0未完成
            if ($actions->row->after_type == 2 && $actions->row->after_status == 0) {
                if ($actions->row->status == 0) {
                    $actions->append("    <a class='btn btn-xs action-btn btn-success grid-row-pass-status' data-id='{$actions->getKey()}'><i class='fa fa-check' title='审核通过'>审核通过</i></a>    ");
                    $actions->append("    <a class='btn btn-xs action-btn btn-danger grid-row-refuse' id='openbtn' data-id='{$actions->getKey()}'><i class='fa fa-close' title='审核拒绝'>审核拒绝</i></a>    ");
                } else if($actions->row->status ==1){
                    if (!empty($actions->row->logis_num) && !empty($actions->row->logis_code)) {
                        $actions->append("<a class='btn btn-xs action-btn btn-success grid-row-pass' data-id='{$actions->getKey()}'><i class='fa fa-check' title='同意退款'>同意退款</i></a>");
                    }
                }
            }
        });
        Admin::html('<div class="overlay" id="overlay"></div>
<div class="popup" id="popup">
        <label>拒绝原因</label><br><br>
        <textarea rows="5" cols="10" id="fruits_id" style="width: 172px; height: 106px;"></textarea>
        <br><br>
        <input type="hidden" name="is_submitted" id="is_submitted" value="0" />
        <button id="closeDiv" class="grid-row-close">取消</button>
        <button type="submit" class="grid-row-submit">确认</button>
</div>');
        Admin::style('/* 遮罩层样式 */
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            display: none; /* 默认隐藏 */
        }

        /* 弹窗样式 */
        .popup {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 5px;
            display: none; /* 默认隐藏 */
            width: 216px;
            text-align:center;
        }
        label {
            width: 100px;
            margin-bottom: 10px;
        }

        input[type="text"], select {
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 12px;
            color: #555;
        }

        select option {
            color: #555;
        }
        button {
            padding: 5px 17px;
            border-radius: 3px;
            border: none;
            background-color: #236dc2;
            color: #fff;
            cursor: pointer;
        }
        button:hover {
            background-color: #0069d9;
        }');
        $this->script = <<<EOT
        //审核通过
        $('.grid-row-pass-status').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认同意通过审核吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'POST',
                        dataType: 'json',
                        url: '/admin/approve/',
                        data:{
                            _token:LA.token,
                            id:id,
                        },
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });
        //同意退款
        $('.grid-row-pass').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认同意该用户的退款申请吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'POST',
                        dataType: 'json',
                        url: '/admin/agree/',
                        data:{
                            _token:LA.token,
                            id:id,
                        },
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });

        //拒绝处理打开层
        $('.grid-row-refuse').unbind('click').click(function() {
             popup.style.display='block';
             overlay.style.display='block';
             var id = $(this).data('id');
             $("#is_submitted").val(id);
        });
        //关闭层
         $('.grid-row-close').unbind('click').click(function() {
            popup.style.display='';
            overlay.style.display='';
        });
        //拒绝退款处理
        $('.grid-row-submit').unbind('click').click(function() {
            var id = $("#is_submitted").val()
            var fruits = $("#fruits_id").val();
            if (fruits ==''){
                swal('请填写拒绝原因', '', 'error');
                return false;
            }
            $.ajax({
                        method: 'POST',
                        dataType: 'json',
                        url: '/admin/refuse/',
                        data:{
                            _token:LA.token,
                            id:id,
                            cause:fruits,
                        },
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                            popup.style.display='';
                            overlay.style.display='';
                        }
                    });
        });
EOT;
        Admin::script($this->script);
        $grid->column('id', __('Id'));
        $grid->fixColumns(0, 1);//固定列可滑动列表
        $grid->column('order_sn', __('订单号'));
        $grid->column('goods_status', __('客户是否收货'))->display(function () {
            $option = [
                1 => "已收货",
                2 => "未收货",
            ];
            return $option[$this->goods_status] ?? '';
        });
        $grid->column('goods_num', __('商品数量'));
        $grid->column('back_reason', __('退款原因'))->display(function () {
            $option = [
                "1"=>"商品无货",
                "2"=>"发货时间问题",
                "3"=>"不想要了",
                "4"=>"商品错选/多选",
                "5"=>"地址信息填写错误",
                "6"=>"价格高于其他平台",
                "7"=>"没用/少用/错用优惠",
            ];
            return $option[$this->back_reason] ?? '';
        });
        $grid->column('money', __('退款金额'));
        $grid->column('afterAddresses', __('寄件地址'))->display(function () {
            $area = new Area();
            $province_name = $area->where('code', $this->address->province_id ?? 0)->value('name');
            $city_name = $area->where('code', $this->address->city_id ?? 0)->value('name');
            $district_name = $area->where('code', $this->address->district_id ?? 0)->value('name');
            $detail = $this->address->detail ?? '';
            if (!empty($province_name) && !empty($city_name) && !empty($district_name)) {
                return '收件人:' . $this->address->name . '电话:' . $this->address->phone . '详细地址:' . $province_name . '->' . $city_name . '->' . $district_name . '->' . $detail;
            }
        });
        $grid->column('images', __('上传凭证'))->display(function () {
            return $this->images;
        })->lightbox(['width' => 50, 'height' => 50]);
        $grid->column('describe', __('补充描述'));
        $grid->column('logis_company', __('物流公司'));
        $grid->column('logis_num', __('退货物流单号'));

        $grid->column('status', __('审核状态'))->using([
            0 => '待审核',
            1 => '已通过',
            2 => '驳回',
        ])->dot([
            0 => 'danger',
            1 => 'success',
            2 => 'primary',
        ]);
        $grid->column('after_type', __('退款类型'))->display(function () {
            $option = [
                1 => "仅退款",
                2 => "退货退款",
                3 => "换货",
            ];
            return $option[$this->after_type] ?? '';
        });

        $grid->column('after_status', __('售后状态'))->using([
            0 => '未完成',
            1 => '已完成',
        ])->dot([
            0 => 'danger',
            1 => 'success',
        ]);

        $grid->column('ordergoods.goods_name', '订单详情')->expand(function ($model) {
            $order = $model->ordergoods()->take(10)->get()->map(function ($order) {
                return $order->only(['id', 'goods_name', 'goods_img', 'goods_num', 'goods_price', 'pay_price', 'created_at']);
            });
            $width = 200;
            $height = 200;
            foreach ($order as $key => $val) {
                $src = Url::getHttpHost() . 'upload/' . $val['goods_img'] ?? '';
                $val['goods_img'] = "<img src='$src' style='max-width:{$width}px;max-height:{$height}px' class='img' />";
                $order[$key] = $val;
            }
            return new Table(['ID', '订单名称', '商品图片', '订单数', '订单价格', '支付价格', '创建时间'], $order->toArray());
        });
        $grid->column('reject_reason', __('驳回原因'))->limit(30)->ucfirst();
        $grid->column('created_at', __('添加时间'));
        $grid->column('updated_at', __('修改时间'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(AfterSales::findOrFail($id));
        $show->panel()->tools(function ($tools) {
            $tools->disableDelete();//禁用删除
            $tools->disableEdit();//禁止修改
        });
        $show->field('id', __('Id'));
        $show->field('after_type', __('退货方式'))->as(function () {
            $option = [
                1 => "仅退款",
                2 => "退货退款",
                3 => "换货",
            ];
            return $option[$this->after_type] ?? '';
        });
        $show->field('order_id', __('订单ID'));
        $show->field('order_sn', __('订单号'));
        $show->field('goods_status', __('客户是否收货'))->as(function () {
            $option = [
                1 => "已收货",
                2 => "未收货",
            ];
            return $option[$this->goods_status] ?? '';
        });
        $show->field('goods_num', __('商品数量'));
        $show->field('back_reason', __('退款原因'))->as(function () {
//            $option = [
//                1 => "不想要了",
//                2 => "看到更便宜的商品",
//                3 => "产品款式选错了",
//                4 => "收货地址/手机号码填错了",
//                5 => "有优惠券未使用",
//                6 => "缺货",
//                7 => "我要退款(无需退货)",
//                8 => "已收到货(我要退货退款）",
//                9 => "其他原因",
//
//            ];
            $option = [
                "1"=>"商品无货",
                "2"=>"发货时间问题",
                "3"=>"不想要了",
                "4"=>"商品错选/多选",
                "5"=>"地址信息填写错误",
                "6"=>"价格高于其他平台",
                "7"=>"没用/少用/错用优惠",
            ];
            return $option[$this->back_reason] ?? '';
        });
        $show->field('money', __('退款金额'));

        $show->field('province_id', __('省'))->unescape()->as(function () {
            $name = (new Area())->where('code', $this->address->province_id ?? 0)->value('name');
            return $name;
        });
        $show->field('city_id', __('市'))->unescape()->as(function () {
            $name = (new Area())->where('code', $this->address->city_id ?? 0)->value('name');
            return $name;
        });
        $show->field('district_id', __('县'))->unescape()->as(function () {
            $name = (new Area())->where('code', $this->address->district_id ?? 0)->value('name');
            return $name;
        });
        $show->field('address.detail', __('详细地址'));
        $show->field('address.name', __('收件人'));
        $show->field('address.phone', __('联系电话'));

        $show->field('images', __('上传凭证'))->as(function ($images) {
            return $images;
        })->image(Url::getHttpHost() . 'upload/', 100, 100);

        $show->field('describe', __('补充描述'));
        $show->field('logis_company', __('物流公司'));
        $show->field('logis_num', __('订单号'));
        $show->field('status', __('审核状态'))->as(function () {
            $option = [
                1 => "审核通过",
                2 => "驳回",
            ];
            return $option[$this->status] ?? '';
        });
        $show->field('after_status', __('售后状态'))->as(function () {
            $option = [
                0 => "未完成",
                1 => "已完成",
            ];
            return $option[$this->after_status] ?? '';
        });
        $show->field('logis_code', __('物流公司编码'));
        $show->field('order_goods_id', __('订单商品表'));//订单商品详情
        $show->field('reject_reason', __('驳回原因'))->limit(30)->ucfirst();
        $show->field('order_source', __('商品类别'))->as(function () {
            $option = [
                1 => "工作室商品",
                2 => "供应商商品",
            ];
            return $option[$this->order_source] ?? '';
        });
        $show->field('works_name', __('工作室'))->as(function () {
            return $this->works->work_name ?? '';
        });
        $show->field('suppliers_name', __('供应商'))->as(function () {
            $name = (new AdminUser())->where([["id", '=', $this->suppliers_id]])->value("name");
            return $name ?? '';
        });
        $show->field('created_at', __('添加时间'));
        $show->field('updated_at', __('修改时间'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new AfterSales());
        $form->radio('after_type', __('退货方式'))->options(['1' => '仅退款', '2' => '退货退款', '3' => '换货'])->default('1');
//        $form->number('order_id', __('Order id'));
        $form->text('order_sn', __('订单号'));
        $form->radio('goods_status', __('客户是否收货'))->options(['1' => '已收货', '2' => '未收货'])->default('2');
        $form->number('goods_num', __('商品数量'));
        $ba_reson = [
            "1"=>"商品无货",
            "2"=>"发货时间问题",
            "3"=>"不想要了",
            "4"=>"商品错选/多选",
            "5"=>"地址信息填写错误",
            "6"=>"价格高于其他平台",
            "7"=>"没用/少用/错用优惠",
            ];
        $form->radio('back_reason', __('退款原因'))->options($ba_reson);

        $form->decimal('money', __('退款金额'));
//        $form->number('coupon_id', __('优惠券'));
//        $form->number('address_id', __('寄件地址'))->hidden();
        $form->multipleFile('images', __('上传凭证'))->uniqueName()->removable();
        $form->text('describe', __('补充描述'));
        $form->text('logis_company', __('物流公司'));
        $form->text('logis_num', __('物流单号'));
        $status = [
            'on' => ['value' => 1, 'text' => '审核通过', 'color' => 'default'],
            'off' => ['value' => 2, 'text' => '驳回', 'color' => 'primary'],
        ];
        $form->switch('status', __('审核状态'))->states($status)->default(2);
        $afterStatus = [
            'on' => ['value' => 0, 'text' => '未完成', 'color' => 'default'],
            'off' => ['value' => 1, 'text' => '已完成', 'color' => 'primary'],
        ];
        $form->switch('after_status', __('处理状态'))->states($afterStatus)->default(0);
        $form->text('logis_code', __('物流公司编码'));
        $form->saving(function ($form) {
            $form->ignore(['address_id']);//忽略字段,提交忽略字段
        });

        return $form;
    }
}
